﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Data.SQLite;
using System.Diagnostics;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using PluginCommon;
using Remider.Entity;
using Remider.Forms;
using Remider.Utility;
using SQLiteHelper;
using WinAPI.User32;
using Timer = System.Threading.Timer;

namespace Remider
{
    public partial class MainUserControl : PluginFormBase
    {
        public delegate void ShowTipDelegate(TipForm tipForm);


        public MainUserControl()
        {
            InitializeComponent();

            MySqLiteFactory.ConnectionString =
                    string.Format("Data Source={0}\\DB\\sql.db3;Pooling=true;FailIfMissing=false", Application.StartupPath);
            BindAppointTask();
            if (!TimerUtility.Started())
            {
                TimerUtility.AppointmentOccured += TimerUtility_AppointmentOccured;
                TimerUtility.Start();
            }
        }

        private void AddButton_Click(object sender, EventArgs e)
        {
            var appointForm = new AppointForm();
            appointForm.ShowDialog(this);
            if (appointForm.Current != null)
            {
                BindAppointTask();
            }
        }

        private void BindAppointTask()
        {
            AppointmentListView.Items.Clear();
            AppointmentStore.LoadAppointTask();
            AppointmentStore.GetLock();
            foreach (var currentAppointment in AppointmentStore.CurrentAppointments)
            {
                AppointmentListView.Items.Add(BuildListViewItem(currentAppointment));
            }
            AppointmentStore.ReleaseLock();
        }

        private void TimerUtility_AppointmentOccured(Appointment appointment)
        {
            appointment.UpdateLastRunTime(DateTime.Now);

            if ("自动关机" == CacheManager.AppointActionType[appointment.ActionType])
            {
                appointment.SetNextRunDate();
                User32Dll.ShutDown();
            }
            else if ("执行程序" == CacheManager.AppointActionType[appointment.ActionType])
            {
                var args = appointment.Content.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                Process.Start(args[0], args[1]);
                appointment.SetNextRunDate();
            }
            else if ("气泡提示" == CacheManager.AppointActionType[appointment.ActionType])
            {
                var tipForm = new TipForm { Current = appointment };
                this.Invoke(new ShowTipDelegate(ShowTip), new object[] { tipForm });
            }
        }

        private static ListViewItem BuildListViewItem(Appointment appointment)
        {
            var items = new[] { CacheManager.AppointmentType[appointment.AppointmentType], 
                        appointment.Title,
                        appointment.Content, 
                        appointment.LastRunDate.ToString(), 
                        appointment.NextRunDate.ToString(), 
                        appointment.LoopInt.ToString(), 
                        appointment.IsDone };
            var listViewItem = new ListViewItem(items) { Tag = appointment };
            return listViewItem;
        }

        private void ShowTip(TipForm tipForm)
        {
            tipForm.Show();
            tipForm.Closed += new EventHandler(TipForm_Closed);
        }

        private void TipForm_Closed(object sender, EventArgs e)
        {
            BindAppointTask();
        }

        private void AppointmentListView_DoubleClick(object sender, EventArgs e)
        {
            if (AppointmentListView.SelectedItems.Count > 0)
            {
                var appointForm = new AppointForm() { Current = (Appointment)AppointmentListView.SelectedItems[0].Tag };
                appointForm.ShowDialog(this);
                BindAppointTask();
            }
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (AppointmentListView.SelectedItems.Count > 0)
            {
                var appointment = (Appointment)AppointmentListView.SelectedItems[0].Tag;
                if (appointment != null)
                {
                    appointment.SetDelete();
                    BindAppointTask();
                }
            }
        }
    }
}
